package com.lvhx.springboot.base;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 抽象聚合类，里面包含了被更改信息的Map、是否改了数据、聚合版本号
 * 定义了更新和删除聚合的方法
 * @param <I>
 */
public abstract class AbstractAggregateRoot<I> implements AggregateRoot, Serializable {
    private static final long serialVersionUID = 1L;
    private boolean isDeleted =false;
    private boolean isDirty = false;
    private Map<String,Object> changedCache = new HashMap<>();
    private boolean isInitializing = true;
    private Long version;


    protected boolean isInitializing(){
        return isInitializing;
    }

    public void markInitialized(){
        isInitializing = false;
    }

    public void markForDeletion(){
        this.isDeleted = true;
        this.unMarkDirty();
    }

    protected void markDirty(){
        this.isDirty = true;
    }

    protected void unMarkDirty(){
        this.isDirty = false;
    }

    protected boolean isDeleted(){
        return isDeleted;
    }

    protected boolean isDirty(){
        return  isDirty;
    }

    @Override
    public Object getIdentifier() {
        return null;
    }

    @Override
    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version){
        if (!isInitializing()){
            throw new RuntimeException("版本号不允许手动手动修改！");
        }
        this.version = version;
    }

    @Override
    public void persist() {
        int rows = 0;
        if (this.isDeleted()){
            rows = this.doDelete();
        }else {
            rows = this.doUpdate();
        }
        if (rows == 0){
            throw new RuntimeException("更新聚合异常！！！");
        }

    }


    protected abstract int doDelete();

    protected abstract int doUpdate();

    public Map<String,Object> getChangedCache(){
        return changedCache;
    }
}
